package com.linshengjian.snowball.signal;

import com.linshengjian.snowball.signal.event.SignalEvent;
import com.linshengjian.snowball.signal.service.ISignalHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import javax.annotation.PostConstruct;

@Slf4j
@Configuration
@EnableConfigurationProperties(SignalProperties.class)
public class SignalConfig {

    @Autowired
    private SignalProperties properties;
    @Autowired
    private ApplicationContext context;

    @PostConstruct
    private void init() {
    }

    @EventListener
    public void signal(SignalEvent event) throws IllegalAccessException, InstantiationException, NoSuchMethodException {

        Class<ISignalHandler> handlerClass = (Class<ISignalHandler>) properties.getType().get(event.getSignal().getMethod());
        if (handlerClass == null) {
            log.warn("没有找到 " + event.getSignal().getMethod() + " 对应的信号事件实现类");
            return;
        }

        ISignalHandler handler;
        try {
            handler = context.getBean(handlerClass);
        } catch (NoSuchBeanDefinitionException e) {
            handler = handlerClass.newInstance();
        }

        switch (event.getSignal().getTargetType()) {
            case Notice:
                handler.notice(event.getMessage());
                return;
            case Platform:
                handler.platform(event.getMessage());
                return;
            case Directional:
                handler.directional(event.getSignal().getTargetObj(), event.getMessage());
                return;
            default:
                throw new NoSuchMethodException("没有找到 " + event.getSignal().getTargetType().name() + "(" + event.getSignal().getTargetType().value() + ") 的实现");
        }
    }
}
